﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AzureDiagMon.Common.Interfaces;

namespace AzureDiagMon.Common.Services
{
    public abstract class ReportableBackgroundService<TServiceState> : BackgroundService, IReportableService<TServiceState> where TServiceState : ServiceState, new()
    {
        private TServiceState serviceState;

        protected void SetServiceState(TServiceState newServiceState)
        {
            lock (SyncRoot)
            {
                serviceState = newServiceState;
            }
        }

        #region Implementation of IReportableService<TServiceState>

        public TServiceState GetServiceState()
        {
            lock (SyncRoot)
            {
                if (serviceState == null)
                    return null;
                return serviceState.Clone() as TServiceState;
            }
        }

        #endregion

        #region Overrides of BackgroundService

        protected override void WorkerWrapper()
        {
            lock (SyncRoot)
            {
                var ss = GetServiceState() ?? new TServiceState();
                ss.IsRunning = true;
                SetServiceState(ss);
            }
            base.WorkerWrapper();
            lock (SyncRoot)
            {
                var ss = GetServiceState() ?? new TServiceState();
                ss.IsRunning = false;
                SetServiceState(ss);
            }
        }

        #endregion
    }
}
